<template>
  <basic-container>
    <section class="haruyuki-bg-color-white">
      <div class="haruyuki-flex-space-between haruyuki-align-items-center">
        <div class="haruyuki-title haruyuki-size-16">
          <i class="el-icon-tickets"></i><span class="haruyuki-ml-6">订单信息</span>
        </div>
        <el-button type="primary" size="mini" @click="clickCopy">一键复制</el-button>
      </div>
      <div class="haruyuki-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="centers">交易信息</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak">订单号：{{ orderInfo.orderCode }}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >付款订单号：{{ orderInfo.rptOrderCode }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >订单创建日期：{{ orderInfo.createTime }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >订单付款日期：{{ orderInfo.orderPayDate }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >订单完成日期：{{ orderInfo.orderCompleteDate }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >订单状态：<span class="picture-preview">{{
                    orderInfo.orderStateName
                  }}</span></span
                >
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <div class="centers">买家信息</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak"
                  >服务商编号：{{ orderInfo.serviceNo }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >服务商名称：{{ orderInfo.serviceName }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >收货人姓名：{{ orderInfo.consignee }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >联系方式：{{ orderInfo.consigneePhone }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >客户经理编号：{{ orderInfo.accountManager }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >客户经理名称：{{ orderInfo.accountManagerName }}</span
                >
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <div class="centers">物流信息</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak"
                  >物流服务：{{ orderInfo.expressTypeName }}</span
                >
              </el-col>
              <el-col :span="24" v-show="orderInfo.expressType">
                <span class="wordBreak"
                  >所属省市区：{{ orderInfo.provinceName }}/{{ orderInfo.cityName }}/{{ orderInfo.areaName }}</span
                >
              </el-col>
              <el-col :span="24" v-show="orderInfo.expressType">
                <span class="wordBreak"
                  >收货地址：{{ orderInfo.consigneeAddress }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >物流公司名称：{{ orderInfo.expressName }}</span
                >
              </el-col>
              <el-col :span="24">
                <span class="wordBreak"
                  >物流单号：{{ orderInfo.expressCode }}</span
                >
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <div class="haruyuki-title haruyuki-size-16 dg-wrap dg-line">
        <i class="el-icon-edit"></i><span class="haruyuki-ml-6">备注信息</span>
      </div>
      <div class="haruyuki-content">
        <div>{{ orderInfo.remark }}</div>
      </div>

      <div class="haruyuki-flex-space-between haruyuki-align-items-center">
        <div class="haruyuki-title haruyuki-size-16">
          <i class="el-icon-tickets"></i
          ><span class="haruyuki-ml-6">商品信息</span>
        </div>
      </div>
      <avue-crud
        :option="option"
        :data="orderZList"
        :page.sync="page"
        ref="crud"
        @current-change="currentChange"
        @size-change="sizeChange"
        @on-load="onLoad"
      >
        <template slot-scope="{ row }" slot="menu">
          <el-button
            size="small"
            type="text"
            v-if="row.orderState === 1"
            @click.stop="faHuo(row.isTransfer, row)"
            >发货</el-button
          >
        </template>
        
        <template slot-scope="{row}" slot="orderState">
          <div class="picture-preview" v-if="row.orderState === 1" @click="getRefund(row)">退款</div>
        </template>

        <template slot-scope="{ row }" slot="useCouponCount">
          <el-tag @click="clickCouponCount(row)" style="cursor: pointer">{{
            row.useCouponCount
          }}</el-tag>
        </template>
      </avue-crud>
    </section>
    <!-- 兑换券列表 -->
    <el-dialog
      title="兑换券列表"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="showCouponCount"
      width="500px"
    >
      <avue-crud
        :option="optionCouponCount"
        :data="dataCouponCount"
        :page.sync="pageCouponCount"
        ref="CouponCount"
        @current-change="currentChangeCouponCount"
        @size-change="sizeChangeCouponCount"
      ></avue-crud>
    </el-dialog>
    <!-- 退款 -->
    <el-dialog
      title="退款"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogRefundVisible"
    >
      <avue-form
        ref="serveForm"
        :option="refundOption"
        v-model="refundForm"
        @submit="refundSubmit"
      ></avue-form>
    </el-dialog>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form
        :model="towPwdForm"
        ref="towPwdForm"
        label-width="0"
        class="demo-ruleForm"
      >
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            {
              required: true,
              message: '二级密码不能为空',
              trigger: ['blur', 'change']
            },
            {
              pattern: /^[0-9]{6}$/,
              message: '二级密码由6位数字组成',
              trigger: ['blur', 'change']
            }
          ]"
        >
          <el-input
            show-password
            v-model.number="towPwdForm.towPwd"
            autocomplete="off"
            placeholder="输入二级密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 不划库发货 -->
    <el-dialog
      title="不划库发货"
      append-to-body
      width="440px"
      ref="fhShowDialog"
      v-if="fhShow"
      :visible.sync="fhShow"
      :before-close="fhBeforeClose"
    >
      <el-form
        :model="fhForm"
        inline
        label-width="100px"
        ref="fhForm"
        :rules="fhFormRules"
        class="demo-ruleForm"
      >
        <el-form-item label="物流方式" prop="expressTypeName">
          <el-input
            v-model="orderInfo.expressTypeName"
            readonly
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <template>
          <el-form-item label="邮费" prop="expressFee">
            <el-input
              v-model="orderInfo.expressFee"
              readonly
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="物流名称" prop="expressName" v-if="orderInfo.expressType">
            <el-input
              v-model="fhForm.expressName"
              autocomplete="off"
              placeholder="请输入物流名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="物流单号" prop="expressCode" v-if="orderInfo.expressType">
            <el-input
              v-model="fhForm.expressCode"
              autocomplete="off"
              placeholder="输入物流单号"
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            readonly
            v-model="orderInfo.remark"
            maxlength="200"
            :autosize="{ minRows: 3 }"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          :disabled="fhDisable"
          @click="fhSubmit()"
          >确认发货</el-button
        >
      </div>
    </el-dialog>
  </basic-container>
</template>
<script>
import {
  apizList,
  apiDetail,
  apiCouponList,
  apiFaHuo,
  refundOrder
} from '@/api/rb-oem/shop/orderList'

import md5 from 'js-md5'
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      // str----不划库
      fhShow: false,
      fhDisable: false,
      fhForm: {
        expressCode: '',
        expressName: ''
      },
      fhFormRules: {
        expressCode: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        expressName: [
          { required: true, message: '请输入物流名称', trigger: 'blur' }
        ]
      },
      // end----不划库
      orderCode: '', //订单编号
      orderInfo: {}, //订单信息
      // str----子订单列表
      orderZList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        // height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        searchMenuSpan: 24,
        columnBtn: false,
        // menu:false,
        menuWidth: 100,
        refreshBtn: false,
        searchBtn: false,
        selectClearBtn: false,
        indexLabel: '序号',
        selection: false,
        column: [
          {
            label: '商品名称',
            prop: 'productName',
            type: 'input',
            overHidden: true,
            minWidth: 250
          },

          {
            label: '型号名称',
            prop: 'specificationName',
            type: 'input',
            overHidden: true,
            minWidth: 130
          },
          {
            label: '子订单编号',
            prop: 'subOrderCode',
            type: 'input',
            width: 200
          },
          {
            label: '行业分类',
            prop: 'classIndustryName',
            type: 'input',
            minWidth: 180,
            overHidden: true
          },
          {
            label: '行业大类',
            prop: 'classSuperName',
            type: 'input',
            minWidth: 150,
            overHidden: true
          },
          {
            label: '行业小类',
            prop: 'classSubName',
            type: 'input',
            minWidth: 150,
            overHidden: true
          },
          {
            label: '品牌名称',
            prop: 'classBrandName',
            type: 'input',
            overHidden: true,
            minWidth: 100
          },
          {
            label: '单价',
            prop: 'price',
            type: 'input',
            overHidden: true,
            minWidth: 100
          },
          {
            label: '数量',
            prop: 'num',
            type: 'input',
            overHidden: true,
            minWidth: 150
          },
          {
            label: '兑换券',
            prop: 'useCouponCount',
            type: 'input',
            overHidden: true,
            minWidth: 220
          },
          {
            label: '实付金额',
            prop: 'realPayAmt',
            type: 'input',
            overHidden: true
          },
          {
            label: '是否划拨',
            prop: 'isTransferName',
            type: 'input',
            overHidden: true
          },
          {
            label: '售后',
            prop: 'orderState',
            type: 'input',
            overHidden: true,
          },
          {
            label: '订单状态',
            prop: 'orderStateName',
            type: 'input',
            overHidden: true
          }
        ]
      },
      // end----子订单列表
      // str----兑换券列表
      showCouponCount: false,
      dataCouponCount: [],
      pageCouponCount: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        subOrderCode: ''
      },
      optionCouponCount: {
        // height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        searchMenuSpan: 24,
        columnBtn: false,
        menu: false,
        menuWidth: 100,
        refreshBtn: false,
        searchBtn: false,
        selectClearBtn: false,
        indexLabel: '序号',
        selection: false,
        column: [
          {
            label: '券类型',
            prop: 'couponTypeName',
            type: 'input',
            overHidden: true,
            // width: 140
          },
          {
            label: '券码',
            prop: 'couponCode',
            type: 'input',
            overHidden: true,
          },
          
        ]
      },
      // end----兑换券列表
      // str----退款
      dialogRefundVisible: false,
      refundForm: {},
      refundOption: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        refreshBtn: false,
        emptyBtn:false,
        column: [
          {
            label: '退款金额',
            prop: 'refundAmount',
            type: 'number',
            value: null,
            // maxRows: '',
            // minRows: '0',
            // step: '1',
            // precision: '2',
            // dataType: 'number',
            controls:false,
            disabled:true,
            rules: [
              {
                required: true,
                message: '请输入退款金额',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '退款理由',
            prop: 'refundReason',
            type: 'textarea',
            span: 24,
            minRows: 2,
            rules: [
              {
                required: true,
                message: '请输入退款理由',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      twoPwdShow: false,
      towPwdForm: {
        towPwd: ''
      }
      // end-----退款
    }
  },
  computed: {
    ...mapGetters(["hasPayPwd"]),
    exhibition() {
      return (val) => {
        if (val == '' || val == '-1' || val == '0.00') {
          return (val = 0)
        } else {
          return val
        }
      }
    },
    // 交易状态
    rptPayStateType() {
      return (row) => {
        if (row.rptPayState == 0) {
          return '#E6A23C' //未支付
        } else if (row.rptPayState == 1 && row.rptIsRefund !== 0) {
          return '#6463bf' //支付成功（已退款）
        } else if (row.rptPayState == 1) {
          return '#67C23A' //支付成功
        } else if (row.rptPayState == 2) {
          return '#909399' //支付失败
        } else if (row.rptPayState == 3) {
          return '#909399' //取消支付
        } else if (row.rptPayState == 4) {
          return '#909399' //退款中
        } else if (row.rptPayState == 5) {
          return '#2fdeebf2' //已退款
        } else if (row.rptPayState == 6) {
          return '#909399' //退款失败
        } else {
          return '#909399'
        }
      }
    }
  },
  created() {
    this.infoData()
  },
  methods: {
    // 复制
    clickCopy() {
      // ht 字符串 | ht格式别乱动
let ht = `
收件人：${this.orderInfo.consignee}
联系方式：${this.orderInfo.consigneePhone}
所属省市区：${ this.orderInfo.provinceName }/${ this.orderInfo.cityName }/${ this.orderInfo.areaName }
收货地址：${this.orderInfo.consigneeAddress}
`;
      const save = function (e) {
        e.clipboardData.setData("text/plain", ht);
        e.preventDefault(); // 阻止默认行为
      };
      const once = {
        once: true,
      };
      document.addEventListener("copy", save, once); // 添加一个copy事件
      document.execCommand("copy"); // 执行copy方法
      this.$message({ message: "复制成功", type: "success" });
    },
    // 兑换券列表 打开
    clickCouponCount(row) {
      if (row.useCouponCount) {
        this.showCouponCount = true
        this.pageCouponCount.subOrderCode = row.subOrderCode

        this.onLoadCouponCount({
          subOrderCode: this.pageCouponCount.subOrderCode
        })
      }
    },
    currentChangeCouponCount(currentPage) {
      this.pageCouponCount.currentPage = currentPage

      this.onLoadCouponCount({
        subOrderCode: this.pageCouponCount.subOrderCode
      })
    },
    sizeChangeCouponCount(pageSize) {
      this.pageCouponCount.pageSize = pageSize

      this.onLoadCouponCount({
        subOrderCode: this.pageCouponCount.subOrderCode
      })
    },
    onLoadCouponCount(params = {}) {
      apiCouponList(
        this.pageCouponCount.currentPage,
        this.pageCouponCount.pageSize,
        params
      ).then((res) => {
        const data = res.data.data
        this.pageCouponCount.total = data.total
        this.dataCouponCount = data.records
      })
    },
    // 不划库发货
    fhSubmit() {
      let that = this
      this.$refs.fhForm.validate((valid) => {
        if (valid) {
          that.fhDisable = true
          let param = {
            ...this.fhForm,
            orderCode: that.orderInfo.orderCode
          }
          apiFaHuo(param).then(
            (res) => {
              this.$refs.fhForm.resetFields()
              that.fhShow = false
              that.fhDisable = false
              this.fhForm.subOrderCode = ''

              that.$message({
                type: 'success',
                message: res.data.msg
              })

              // that.infoData() //详情接口
              that.onLoad(that.page, { orderCode: that.orderCode }) //子订单列表接口
            },
            (error) => {
              that.fhDisable = false
            }
          )
        } else {
          return false
        }
      })
    },
    fhBeforeClose(done) {
      this.$refs.fhForm.resetFields()
      this.fhForm.subOrderCode = ''
      this.fhDisable = false

      done()
    },
    // 发货
    faHuo(type, row) {
      if (type === 0) {
        // 不划库发货
        this.fhShow = true
        this.fhForm.subOrderCode = row.subOrderCode
      } else if (type === 1) {
        // 划库发货

        let param = {
          subOrderCode:row.subOrderCode,
          orderCode:this.orderInfo.orderCode
        }
        this.$router.push({ path: '/rb-oem/shop/orderListDetails', query: param})
      }
    },
    
    // 二级密码 关闭回调
    handleCloseTwoPwd(done) {
      this.towPwdForm.towPwd = ''
      done()
    },
    // 二级密码 确定
    twoPwdSubmit() {
      let that = this
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          refundOrder({
            // orderCode: that.orderInfo.rptOrderCode,
            ...that.refundForm,
            password: md5(that.towPwdForm.towPwd + '')
            // payPwd:that.towPwdForm.towPwd
          }).then(
            () => {
              that.twoPwdShow = false
              that.towPwdForm.towPwd = ''
              that.dialogRefundVisible = false
              that.$message({
                type: 'success',
                message: '退款成功!'
              })
              that.$refs.serveForm.resetForm()
              that.refundForm = {}
              // that.infoData();//详情接口
              that.onLoad(that.page, { orderCode: that.orderCode }) //子订单列表接口
            },
            (error) => {
              that.dialogRefundVisible = false
            }
          )
        } else {
          return false
        }
      })
    },
    /* 退款 dialog */
    getRefund(row) {
      this.$set(this.refundForm,'subOrderCode',row.subOrderCode)

      const column = this.findObject(this.refundOption.column, "refundAmount");
      column.value = row.realPayAmt;
      // column.maxRows = row.price;
      this.dialogRefundVisible = true;
    },
    /* 提交 退款金额 */
    refundSubmit(row, done) {
      console.log('退款金额',this.hasPayPwd);
      if (this.hasPayPwd) {
        this.twoPwdShow = true
        done()
      } else {
        this.$confirm('请您先设置二级密码，再操作！', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          this.$router.push({ path: '/info/index', query: { index: 2 } })
        })
      }
    },
    /* 页面加载 初始化请求详情接口 */
    infoData() {
      this.orderCode = this.$route.query.orderCode

      apiDetail({ orderCode: this.orderCode }).then((res) => {
        this.orderInfo = res.data.data
      })

      this.$store.dispatch("apiHasPayPwd")

    },
    // 子订单
    onLoad(page, params = {}) {
      params.orderCode = this.orderCode || this.orderInfo.orderCode

      apizList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data
        this.page.total = data.total
        this.orderZList = data.records
      })
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    /* 返回页面 */
    goBack() {
      this.$router.$avueRouter.closeTag()
      this.$router.replace({ path: '/rb-oem/shop/orderList' })
    }
  }
}
</script>

<style lang="scss" scoped>
.picture-preview {
  color: #409eff;
  cursor: pointer;
}

.merchant-title {
  font-weight: bold;
}

/deep/ .avue-crud__menu {
  display: none !important;
}
.wordBreak {
  word-break: break-word;
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
.centers {
  text-align: center;
}
::v-deep .el-form--inline .el-form-item__content {
  width: calc(100% - 120px);
}
::v-deep .el-form--inline .el-form-item {
  width: 100%;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>